package com.cjm.algorithm.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FourSum18 {
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length < 4) return res;
        int len = nums.length;
        Arrays.sort(nums);
        // 遍历两个数然后进行双指针(O(N^3)
        for (int i = 0; i < len - 3; i++) {
            // 剪枝(注意细节:因为可能nums[i]为负数就还不能剪枝[-5,-4,-3,-2],target=-14)
            if (nums[i] >= 0 && nums[i] > target) break;
            // a去重
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < len - 2; j++) {
                // 剪枝(注意细节)
                if (nums[j] >= 0 && nums[i] + nums[j] > target) break;
                // b去重
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;
                // 双指针
                int l = j + 1, r = len - 1;
                while (l < r) {
                    // [i,j,l,r]
                    int sum = nums[i] + nums[j] + nums[l] + nums[r];
                    if (sum < target) l++;
                    else if (sum > target) r--;
                    else {
                        res.add(Arrays.asList(nums[i], nums[j], nums[l], nums[r]));
                        // 去重
                        while (l < r && nums[l] == nums[l + 1]) l++;
                        while (l < r && nums[r] == nums[r - 1]) r--;
                        l++;
                        r--;
                    }
                }
            }
        }
        return res;
    }

    public static List<List<Integer>> fourSum1(int[] nums, int target) {
        if (nums == null || nums.length < 4) {
            return new ArrayList<>();
        }
        int len = nums.length;
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < len - 3; i++) {
            if (i > 0 && nums[i] > target) break;
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < len - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;
                int l = j + 1, r = len - 1;
                while (l < r) {
                    int sum =  nums[i] + nums[j]+nums[l] + nums[r] ;
                    if (sum == target) {
                        res.add(Arrays.asList(nums[i], nums[j], nums[l], nums[r]));
                        while (l < r && nums[l] == nums[l + 1]) l++;
                        while (l < r && nums[r - 1] == nums[r]) r--;
                        l++;
                        r--;
                    } else if (sum > target) {
                        r--;
                    } else {
                        l--;
                    }
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        System.err.println(fourSum1(new int[]{1,0,-1,0,-2,2}, 0));
    }
}
